package com.lkd.job;

import ch.qos.logback.classic.spi.EventArgUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vendingMachineService;

    @XxlJob("supplyJobHandler")
    public ReturnT<String> supplyJobHandler(String param) throws Exception {

        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();

        //分片总数
        int total = shardingVo.getTotal();
        //当前分片索引
        int index = shardingVo.getIndex();

        log.info("分片参数 当前分片索引{} 总分片数{}", index, total);

        //1.查出所有运营状态的售货机
        LambdaQueryWrapper<VendingMachineEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
        .apply("mod(id,"+total+")="+index);  //对id取模
        List<VendingMachineEntity> vendingMachineEntityList = vendingMachineService.list(wrapper);

        //2.每个售货机均调用第1步的补货业务逻辑
        vendingMachineEntityList.forEach(vm -> {
            XxlJobLogger.log("扫描售货机" + vm.getInnerCode());
            vendingMachineService.sendSupplyTask(vm.getInnerCode());
        });

        return ReturnT.SUCCESS;
    }
}
